import TopSearch from "@/components/TopSearch";
import { PlusOutlined } from "@ant-design/icons";
import Card from "@/components/Card";
import { useEffect, useState } from "react";
import VirtualScoll from "@/components/virtualScoll";
import {
  getMessageList,
  searchMessage,
  setMessageRead,
  type MessageType
} from "@/api/xhr/message/index";
import friendsSocketApiFunc from "@/api/socket/socketFunc/friends.ts";
import { useSelector } from "react-redux";

import { formatMsgTime } from "@/util/index";
import AddGroupComponent from "../commponents/AddGroupComponent";
import SoundManager from "@/util/sound";

const controls = {
  isshowtime: true, //是否显示时间
  isshowmessage: true, //是否显示消息
  isnav: true
};

const MessageList = () => {
  const userinfo = useSelector((state: any) => state.user.userinfo);
  const [searchVal, setsearchVal] = useState("");
  const [showAddGroup, setShowAddGroup] = useState<boolean>(false);
  const [messagelist, setmessagelist] = useState<MessageType[]>([]);
  function AddGroup() {
    setShowAddGroup(true);
  }
  useEffect(() => {
    messageList();
    friendsSocketApiFunc.comfirmFriend = handelSocketComfirmFriend;
    friendsSocketApiFunc.createdGroup = handelSocketCreatedGroup;
    friendsSocketApiFunc.destroyGroup = handelSocketDestroyGroup;
    friendsSocketApiFunc.getMessagelist = handelSocketGetmessageList;
    friendsSocketApiFunc.invitedToGroup = handelSocketInvitedToGroup;
    
    // 添加监听群信息更新的事件
    const handleGroupInfoUpdate = (event: Event) => {
      const customEvent = event as CustomEvent<{ 
        type: string; 
        groupId: number; 
        newName: string 
      }>;
      
      if (customEvent.detail && customEvent.detail.type === "groupName") {
        console.log("收到群名称更新事件:", customEvent.detail);
        
        // 更新消息列表中的群名称
        setmessagelist(prevList => {
          const updatedList = prevList.map(item => {
            if (item.type === "group" && item.id === customEvent.detail.groupId) {
              console.log("更新群聊:", item.name, "->", customEvent.detail.newName);
              return {
                ...item,
                name: customEvent.detail.newName
              };
            }
            return item;
          });
          
          return updatedList;
        });
      }
    };
    
    window.addEventListener("updateGroupInfo", handleGroupInfoUpdate);

    // 添加监听退出群聊和删除群聊的事件
    const handleUpdateMessageList = (e: CustomEvent) => {
      if (e.detail.action === "removeGroup") {
        // 当用户退出群聊时，从消息列表中移除该群聊
        setmessagelist(prevList => 
          prevList.filter(item => 
            !(item.type === "group" && item.id === e.detail.groupId)
          )
        );
      }
    };

    window.addEventListener("updateMessageList", handleUpdateMessageList as EventListener);
    
    return () => {
      friendsSocketApiFunc.comfirmFriend = () => {};
      friendsSocketApiFunc.createdGroup = () => {};
      friendsSocketApiFunc.destroyGroup = () => {};
      friendsSocketApiFunc.getMessagelist = () => {};
      friendsSocketApiFunc.invitedToGroup = () => {};
      
      // 移除事件监听
      window.removeEventListener("updateGroupInfo", handleGroupInfoUpdate);
      window.removeEventListener("updateMessageList", handleUpdateMessageList as EventListener);
    };
  }, []);

  async function searchFunc(searchvalue: string) {
    if (searchvalue) {
      const res = await searchMessage({
        keyword: searchvalue,
        userId: userinfo.id
      });
      if (res.statusCode == 200) {
        const data = res.data.map(item => {
          return {
            ...item,
            time: formatMsgTime(item.lastMessageTime),
            isnew: true
          };
        });
        setmessagelist(data);
      }
    } else {
      messageList();
    }
  }
  function handelSocketCreatedGroup(data: MessageType) {
    console.log("收到创建群组消息:", data);
    
    // 确保有格式化的时间
    const formattedData = {
      ...data,
      time: formatMsgTime(data.lastMessageTime || new Date().toISOString())
    };
    
    // 创建一个全新的数组引用
    setmessagelist(prevList => {
      const newList = [formattedData, ...prevList];
      console.log("更新后消息列表长度:", newList.length);
      return newList;
    });
  }
  function handelSocketComfirmFriend(data: MessageType) {
    setmessagelist(messagelist => [
      {
        ...data,
        time: formatMsgTime(data.lastMessageTime)
      },
      ...messagelist
    ]);
  }
  function handelSocketDestroyGroup() {
    messageList();
  }
  function handelSocketGetmessageList(data: any) {
    if (data.noMessageNum && data.noMessageNum > 0) {
      SoundManager.getInstance().playMessageSound(false);
    }

    console.log("收到消息列表更新:", data);
    
    setmessagelist(list => {
      // 找到要更新的消息
      let foundMatch = false;
      const updatedList = list.map(item => {
        if (item.id == data.messageId && item.type == data.type) {
          foundMatch = true;
          console.log("找到匹配的会话进行更新");
          return {
            ...item,
            message: data.message,
            noMessageNum: data.noMessageNum,
            time: formatMsgTime(data.lastMessageTime),
            lastMessageTime: data.lastMessageTime
          };
        }
        return item;
      });
      
      if (!foundMatch) {
        console.log("未找到匹配的会话");
      }
      
      // 创建新数组引用并排序
      const sortedList = [...updatedList].sort((a, b) => {
        return (
          new Date(b.lastMessageTime).getTime() -
          new Date(a.lastMessageTime).getTime()
        );
      });
      
      return sortedList;
    });
  }
  function handelSocketInvitedToGroup(data: MessageType) {
    console.log("收到被邀请进群消息:", data);
    
    // 确保有格式化的时间
    const formattedData = {
      ...data,
      time: formatMsgTime(data.lastMessageTime || new Date().toISOString())
    };
    
    // 创建一个全新的数组引用，将新群聊添加到列表顶部
    setmessagelist(prevList => {
      const newList = [formattedData, ...prevList];
      console.log("更新后消息列表长度:", newList.length);
      return newList;
    });
  }
  async function messageList() {
    const res = await getMessageList({ userId: userinfo.id });
    if (res.statusCode == 200) {
      const newmessagelist = res.data.map(item => {
        return {
          ...item,
          time: formatMsgTime(item.lastMessageTime)
        };
      });
      setmessagelist(newmessagelist);
    }
  }
  function handelCardClick(data) {
    if (data.noMessageNum) {
      setMessageRead({
        messageId: data.id,
        type: data.type,
        userId: userinfo.id
      }).then(res => {
        if (res.statusCode == 200) {
          setmessagelist(messagelist => {
            return messagelist.map(item => {
              if (item.id == data.id && item.type == data.type) {
                return {
                  ...item,
                  noMessageNum: 0
                };
              } else {
                return item;
              }
            });
          });
        }
      });
    }
  }
  return (
    <>
      <TopSearch
        value={searchVal}
        setvalue={setsearchVal}
        searchFunc={searchFunc}
      >
        <PlusOutlined onClick={AddGroup} />
      </TopSearch>
      {messagelist.length ? (
        <VirtualScoll
          dataList={messagelist}
          itemHeight={60}
          renderItem={item => {
            return (
              <Card
                key={item.id + item.type}
                item={item}
                controls={controls}
                handelClick={handelCardClick}
              ></Card>
            );
          }}
        ></VirtualScoll>
      ) : (
        <div className="text-sm text-gray-400">暂无数据</div>
      )}
      {showAddGroup ? (
        <AddGroupComponent
          show={showAddGroup}
          setshow={setShowAddGroup}
        ></AddGroupComponent>
      ) : (
        ""
      )}
    </>
  );
};

export default MessageList;
